import schedule
from urllib3.exceptions import NameResolutionError

from service import KeepLiveService, GetInfoService, ConfigService, EmailNoticeService, LogRecoderService
from utils import Util


def task():
    # 1.读取文件配置信息
    config_service = ConfigService.init_config("./data/config/config.ini")
    try:
        # 2.检测服务心跳
        hasNetwork = KeepLiveService.keepLive(config_service)  # 配置读取config对象
        if not hasNetwork:
            return

        # 3.获取并存储教务官网相应信息
        GetInfoService.main(config_service)

        # 4.检查并推送错误日志，报告管理员
        EmailNoticeService.check_and_send_message(config_service)
    except FileNotFoundError as e:
        print("请先修改项目路径，保证文件配置成功！！！")
        print(e)
    except NameResolutionError as e:
        LogRecoderService.logger.error(e)
    except Exception as e:
        LogRecoderService.logger.error(e)
        Util.write_error_file(ConfigService.get_config(config_service, 'script', 'error_path'), e)
    finally:
        # 5.再次检测附件是否删除完毕
        Util.removeAllFiles(ConfigService.get_config(config_service, 'script', 'file_download'))


def main():
    # 1.每半小时执行一次任务
    task()
    # schedule.every(30).minutes.do(task).tag(task)
    # print("Please enter Ctrl+C to exit")
    # while True:
    #     schedule.run_pending()


if __name__ == '__main__':
    main()
